package com.leo.algorithm.linked;

/**
 *  反转整个链表
 */
public class Reverse {

    public static void main(String[] args) {


    }


    /**
     * 循环反转链表
     * @param head
     * @return
     */
    public ListNode loop(ListNode head) {
        ListNode pre = null, cur = head, nxt = head;
        while (cur != null) {
            nxt = cur.getNext();
            // 逐个结点反转
            cur.setNext(pre);
            // 更新指针位置
            pre = cur;
            cur = nxt;
        }
        // 返回反转后的头结点
        return pre;
    }


    /**
     * 递归反转整个链表
     * @param head
     * @return
     */
    public ListNode recursion(ListNode head) {
        if (head.getNext() == null) return head;
        ListNode last = recursion(head.getNext());
        head.getNext().setNext(head);
        head.setNext(null);
        return last;
    }

}
